package com.android.chen.httpdemo;

import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;


public class MainActivity extends Activity {

    final static String phoneUrl = "https://tcc.taobao.com/cc/json/mobile_tel_segment.htm";

    //final String phoneUrl = "http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx/getWeather"; // 定义需要获取的内容来源地址
    private EditText edt_input;
    private TextView tv_result;
    private Button bt_get;
    private Button bt_post;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        edt_input = (EditText)findViewById(R.id.edittext_input);
        tv_result = (TextView)findViewById(R.id.textview_show);

        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());

        bt_get = (Button)findViewById(R.id.button_get);
        bt_get.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Get_url();
            }
        });
        bt_post = (Button)findViewById(R.id.button_post);
        bt_post.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Post_url();
            }
        });
    }



    //使用GET方式
    private void Get_url()
    {
        try{
            String phonenum = edt_input.getText().toString();
            phonenum = phonenum.replace(" ", "%20");
            URL geturl = new URL(phoneUrl + "?tel=" + phonenum);
            HttpURLConnection httpconn = (HttpURLConnection) geturl.openConnection();
            httpconn.setReadTimeout(9000);

            if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK)
            {
                Toast.makeText(getApplicationContext(),"get连接手机在线API成功",
                        Toast.LENGTH_SHORT).show();
                //InputStreamerReader，得到数据流
                InputStreamReader isr = new InputStreamReader(httpconn.getInputStream(),"gbk");
                int i;
                String content = "";
                //read,读取数据
                while ((i = isr.read()) != -1){
                    content = content + (char)i;
                }
                isr.close();
                tv_result.setText(content);
            }
            //关闭连接
            httpconn.disconnect();

        }catch (Exception e)
        {
            Toast.makeText(getApplicationContext(),"get连接手机在线API失败",Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }

    //使用GET方式
    private void Post_url()
    {
        try{
            String phonenum = edt_input.getText().toString();

            URL geturl = new URL(phoneUrl);
            HttpURLConnection httpconn = (HttpURLConnection) geturl.openConnection();

            httpconn.setDoOutput(true);
            httpconn.setDoInput(true);
            httpconn.setRequestMethod("POST");
            httpconn.setUseCaches(false);
            httpconn.setRequestProperty("Content-Type", "application/x-www-from-urlencoded");

            httpconn.setReadTimeout(9000);

            httpconn.connect();
            DataOutputStream out = new DataOutputStream(httpconn.getOutputStream());
            String content = "tel="+ URLEncoder.encode(phonenum,"gbk");//+"&output=xml"
            out.writeBytes(content);
            out.flush();
            out.close();

            //InputStreamerReader，得到数据流
            InputStreamReader isr = new InputStreamReader(httpconn.getInputStream(),"utf-8");
            int i;
            String content_post = "";
            // 读
            while ((i = isr.read()) != -1){
                content_post =  content_post + (char)i;
            }
            isr.close();
            //设置textview
            tv_result.setText(content_post);
            //关闭连接
            httpconn.disconnect();
            Toast.makeText(getApplicationContext(),"post连接手机在线API成功",
                    Toast.LENGTH_SHORT).show();

        }catch (Exception e)
        {
            Toast.makeText(getApplicationContext(),"post连接手机在线API失败",Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
